import { useRequest } from "@/hooks/use-request";
import { useUserStore } from "@/stores/global/user";
import { antdUtils } from "@/utils/antd";
import { t } from "@/utils/i18n";
import { useInViewport, useMount, useUpdateEffect } from "ahooks";
import { Button, Col, Flex, Popconfirm, Row, Space, Table } from "antd";
import { ColumnsType } from "antd/es/table";
import { useRef } from "react";
import { useImmer } from "use-immer";
import { EditDialog } from "./new-edit-plan";
import myService from "./service";

const MyPage = () => {
  const ref = useRef(null);
  const [inViewport] = useInViewport(ref);
  const { currentUser } = useUserStore();
  const [inProgressPlanList, setInProgressPlanList] = useImmer<any[]>([]);
  const [suspendList, setSuspendList] = useImmer<any[]>([]);
  const [showEditDialog, setShowEditDialog] = useImmer({
    isShow: false,
    data: null,
  });

  const { runAsync: getMyInProgressPlan } = useRequest(
    myService.getMyInProgressPlan,
    {
      manual: true,
    }
  );
  const { runAsync: getMySuspendPlan } = useRequest(
    myService.getMySuspendPlan,
    {
      manual: true,
    }
  );

  const { runAsync: deleteItem } = useRequest(myService.deleteItem, {
    manual: true,
  });

  const getInProgressPlan = async () => {
    const [error, data] = await getMyInProgressPlan(currentUser?.id);
    if (error) {
      antdUtils.message?.error(error);
    } else {
      setInProgressPlanList(data as any);
    }
  };
  const getSuspendPlan = async () => {
    const [error, data] = await getMySuspendPlan(currentUser?.id);
    if (error) {
      antdUtils.message?.error(error);
    } else {
      setSuspendList(data as any);
    }
  };

  useMount(async () => {
    getInProgressPlan();
    getSuspendPlan();
  });

  useUpdateEffect(() => {
    if (inViewport) {
      getInProgressPlan();
      getSuspendPlan();
    }
  }, [inViewport]);

  const planColumns = (num: number): ColumnsType<any> => {
    return [
      {
        title: t("PlanName") /**计划名 */,
        dataIndex: "name",
        key: "name",
        width: 200,
        fixed: "left",
      },
      {
        title: t("PlannedStartTime") /**计划开始时间 */,
        dataIndex: "startTime",
        key: "startTime",
        width: 150,
        defaultSortOrder: "descend",
      },
      {
        title: t("planOverTime") /**预计完成时间 */,
        dataIndex: "planOverTime",
        key: "planOverTime",
        width: 150,
      },
      {
        title: t("executeTimeFirst") /** 第一次执行时间*/,
        dataIndex: "executeTimeFirst",
        key: "executeTimeFirst",
        width: 150,
      },
      {
        title: t("overTime") /** 完成时间*/,
        dataIndex: "overTime",
        key: "overTime",
        width: 150,
      },
      {
        title: t("notes") /**备注 */,
        dataIndex: "notes",
        key: "notes",
        width: 400,
        align: "center",
        render: (_, item) =>
          JSON.parse(item.notes ? item.notes : "[]").map((n: any) => {
            return (
              <Row>
                <Col>
                  <a
                    onClick={() => {
                      // navigate(RouterPath.project_plan_note, { state: item })
                    }}
                  >
                    {`${n.time}：${n.info}`}
                  </a>
                </Col>
              </Row>
            );
          }),
      },
      {
        title: t("describe") /**描述 */,
        dataIndex: "describe",
        key: "describe",
        width: 400,
      },
      {
        title: t("QkOmYwne") /**操作 */,
        key: "aaaa",
        width: 150,
        fixed: "right",
        align: "center",
        render: (_, item) => (
          <Space>
            <Button
              size="small"
              onClick={() => {
                setShowEditDialog({ isShow: true, data: item });
              }}
            >
              {t("wXpnewYo") /**编辑 */}
            </Button>
            {item.userid === currentUser?.id ? (
              <Popconfirm
                title={t("DeleteConfirmation") /** 删除确认 */}
                onConfirm={async () => {
                  const [error] = await deleteItem(item.id);
                  if (error) {
                    antdUtils.message?.error(error);
                  } else {
                    switch (num) {
                      case 1:
                        getInProgressPlan();
                        break;
                      case 2:
                        getSuspendPlan();
                        break;
                    }
                  }
                }}
                okText={t("confirm") /**确定 */}
                cancelText={t("cancel") /**取消 */}
              >
                <Button size="small" type="dashed" danger>
                  {t("HJYhipnp") /**删除 */}
                </Button>
              </Popconfirm>
            ) : (
              ""
            )}
          </Space>
        ),
      },
    ];
  };

  return (
    <Flex ref={ref} vertical className=" w-[100%] h-[84vh]">
      <Flex className=" w-[100%] h-[100%]">
        <Flex className=" w-[50%] h-[100%]">
          <Table
            rowKey="id"
            className=" w-[100%] h-[80vh]"
            title={() => t("PlanInProgress") /**执行中的计划 */}
            pagination={false}
            columns={planColumns(1)}
            scroll={{ y: "70vh" }}
            dataSource={inProgressPlanList}
          ></Table>
        </Flex>
        <Flex className=" w-[50%] h-[100%] ml-[10px]">
          <Table
            rowKey="id"
            className=" w-[100%] h-[80vh]"
            title={() => t("SuspendedPlan") /** 暂停的计划*/}
            columns={planColumns(2)}
            pagination={false}
            scroll={{ y: "70vh" }}
            dataSource={suspendList}
          ></Table>
        </Flex>
      </Flex>
      <EditDialog
        setShowEditDialog={setShowEditDialog}
        showEditDialog={showEditDialog}
        onSave={() => {
          getInProgressPlan();
          getSuspendPlan();
        }}
      />
    </Flex>
  );
};

export default MyPage;
